
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
#include <string.h>
#include "./seqstackqueue.h"

#define MAX_SIZE 100

// 运算符优先级判断
int priority(char op);
// 是否是操作数
int isoperator(char ch);

void infixToSuffix(char *infix, char *suffix)
{
    Stack *S = createStack(MAX_SIZE);
    int j = 0;

    printf("infix len=%lu\n", strlen(infix));
    for (int i = 0; i < strlen(infix); i++)
    {
        char ch = infix[i];
        printf("No.%d, to get infix element=%c\n", i, ch);
        if (isoperator(ch))
        {
            while (notEmpty(S) && priority(peek(S)) >= priority(ch))
            {
                suffix[j++] = pop(S);
            }
            push(S, ch);
        }
        else if (ch == '(')
        {
            printf("=No.%d it's (, push statck\n", i);
            push(S, ch);
        }
        else if (ch == ')')
        {
            printf("=No.%d it's ), will pop statck, the statck top=%c\n", i, peek(S));
            while (notEmpty(S) && peek(S) != '(')
            {
                suffix[j++] = pop(S);
            }

            if (isEmpty(S) || peek(S) != '(')
            {
                printf("Invalid Expression--\n");
                return;
            }
            pop(S);
        }
        else if (ch == '\n')
        {
            printf("-->%d [ %c ] infix array end symbol\n", ch, ch);
        }
        else
        {
            suffix[j++] = ch;
            printf(">>add [%c] to suffix array [%d] location\n", ch, j);
        }

        printf("\n");
    }

    while (notEmpty(S))
    {
        int topElement = peek(S);
        if (topElement == '(' || topElement == ')')
        {
            printf("Invalid Expression\n");
            return;
        }
        char remain = pop(S);
        suffix[j++] = remain;
        printf(">>continue add remaining data: %c\n", remain);
    }

    suffix[j] = '\0';
}

int main()
{
    // 9-(2+4*7)/5+3
    char infix[MAX_SIZE];
    // 9247*+5/-3+
    char suffix[MAX_SIZE];

    printf("Enter infix expression: ");
    fgets(infix, MAX_SIZE, stdin);

    infixToSuffix(infix, suffix);
    printf("suffix expression: %s\n", suffix);
    return 0;
}

int priority(char op)
{
    switch (op)
    {
    case '(':
    case ')':
        return 0;
    case '-':
    case '+':
        return 1;
    case '*':
    case '/':
        return 2;
    default:
        return -1;
    }
}

int isoperator(char ch)
{
    // char chs[] = {'+', '-', '*', '/'};
    if (ch == '+' || ch == '-' || ch == '*' || ch == '/')
    {
        printf(">>[%c] is operator\n", ch);
        return 1;
    }
    printf(">>[%c] is not operator\n", ch);
    return 0;
}